package com.zhouyu.mysql;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 大都督周瑜（我的微信: dadudu6789）
 */
public class ConnectionHandlerPerThread extends ChannelInboundHandlerAdapter {

    private SqlParse sqlParse = new SqlParse();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        String sql = in.toString(CharsetUtil.UTF_8);
        System.out.println("接收到sql: " + sql);

        // 先调用解析器解析sql
        // 再调用优化器优化sql
        // 再调用执行器执行sql，执行器内调用innodb存储引擎，最终得到结果，这里结果我们固定都转成String

        String result = sqlParse.mysql_parse(sql);


        // 发送响应
        ByteBuf responseBuffer = Unpooled.copiedBuffer(result, CharsetUtil.UTF_8);
        ctx.write(responseBuffer);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
